/*
 * Copyright (c) 2017年11月02日  by XuanWu Wireless Technology Co., Ltd 
 *             All rights reserved  
 */
package com.zml.entity.sync;

import com.zml.entity.ConfigRecord;
import com.zml.service.BizDataService;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="mailto:zhaominglin@wxchina.com">minglin.Zhao</a>
 * @Description
 * @Date 2017/11/2
 * @Version 1.0.0
 */
public class SysConfig implements SyncTask {

    private static final Logger logger = LogManager.getLogger(SysConfig.class);
    private static String contextPath;

    private Map<String, Object> configMap = new HashMap<String, Object>();
    @Autowired
    private BizDataService bizDataService;

    private int period = 60*1000;//默认值为1分钟，可以从application.yml中配置

    private ReentrantLock lock = new ReentrantLock();

    public void init() {
        run();
    }

    @Override
    public long getPeriod() {
        return period;
    }

    @Override
    public void run() {
        try {
            if(bizDataService == null){
                logger.error("bizDao is null");
            }
            List<ConfigRecord> configs = bizDataService.findAllConfigs();
            for (ConfigRecord config : configs) {
                putConfig(config);
            }
            logger.info("Sync system config success,the size is {}",configMap.size());
        } catch (Exception e) {
            logger.error("Sync system config failed: ", e);
        }
    }

    private void putConfig(ConfigRecord config) throws ParseException {
        lock.lock();
        try {
            if ("int".equalsIgnoreCase(config.getType())) {
                configMap.put(config.getKey(), Integer.parseInt(config.getValue()));
            } else if ("float".equalsIgnoreCase(config.getType())) {
                configMap.put(config.getKey(), Float.parseFloat(config.getValue()));
            } else {
                configMap.put(config.getKey(), config.getValue());
            }
        } finally {
            lock.unlock();
        }
    }

    public boolean updateConfig(ConfigRecord config) {
        if (config == null) {
            return false;
        }
        try {
            bizDataService.updateConfig(config);
            putConfig(config);
            return true;
        } catch (Exception e) {
            logger.error("Update config failed: ", e);
        }
        return false;
    }

    public boolean updateConfig(ConfigRecord config, String oldValue) {
        if (config == null) {
            return false;
        }
        try {
            if (bizDataService.updateConfigWithOldValue(config, oldValue)) {
                putConfig(config);
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("Update config failed: ", e);
        }
        return false;
    }

    public static void setContextPath(String contextPath) {
        SysConfig.contextPath = contextPath;
    }
    public String getSmtpHostname() {
        return (String) configMap.get("smtpHostname");
    }

    public int getSmtpPort() {
        return (Integer) configMap.get("smtpPort");
    }

    public String getSmtpUsername() {
        return (String) configMap.get("smtpUsername");
    }

    public String getSmtpPassword() {
        return (String) configMap.get("smtpPassword");
    }

    public boolean isSmtpSslOn() {
        return (Integer) configMap.get("smtpSslOn") == 1;
    }

    public int getSmtpSslPort() {
        return (Integer) configMap.get("smtpSslPort");
    }

    public String getEmailFrom() {
        return (String) configMap.get("emailFrom");
    }

    @Override
    public String getTaskName() {
        return "SysConfig Task";
    }

    public String getMsgSign() {
        return (String) configMap.get("msgSign");
    }

    public String getImgUploadPath(){
        return (String) configMap.get("imgUploadPath");
    }

    public void setPeriod(int period) {
        this.period = period;
    }
}
